<?php
function game_go(&$arrReturn)
{
    global $db;
    $speNo = $_GET['no'];
    $isToAuto = true;
    $arrReturn['log'] .= LogFormat('begin time:' . date('Y-m-d H:i:s'));
    if (date("H") < 9) {
        //取下期时间
        $sql = "SELECT id,kgtime FROM game28 WHERE kj = 0 AND kgtime > NOW() order by id limit 1";
        $query = $db->query($sql);
        if ($rs = $db->fetch_array($query)) {
            $arrRet['nextid'] = $rs['id'];
            $arrRet['nexttime'] = $rs['kgtime'];
        } else {
            $sql = "select DATE_ADD(NOW(),INTERVAL 60 SECOND) nowtime";
            $query = $db->query($sql);
            $rs = $db->fetch_array($query);
            $arrRet['nextid'] = '0';
            $arrRet['nexttime'] = date('Y-m-d H:i:s', strtotime($rs["nowtime"]));
        }
        $arrReturn['msg'] = 'not in open result time(bj)';
        return;
    }

    $No = intval($speNo);
    if ($speNo == 0) //取最新开奖
    {
        $sql = "select gameno from game_result where gametype = 'gamebj' and isopen = 0 order by gameno desc limit 1";
        $query = $db->query($sql);
        if ($rs = $db->fetch_array($query)) {
            $No = $rs["gameno"];
        } else {
            //保证采集不到但下盘时间快到时自动下注
            $sql = "SELECT id,kgtime,now() as nowtime FROM game28 WHERE kj = 0 AND zdtz_r = 0 AND kgtime > NOW() ORDER BY kgtime LIMIT 1";
            $query = $db->query($sql);
            if ($rs = $db->fetch_array($query)) {
                $NextNo = $rs['id'];
                if (strtotime($rs['kgtime']) - strtotime($rs['nowtime']) < 30) {
                    //自动投注
                    AutoPress($arrReturn, $No - 1, $NextNo);
                }
            }
            $arrReturn['code'] = "ok";
            $arrReturn['msg'] = "no open game record(bj)";
            $arrReturn['log'] .= LogFormat("no open game record(bj)");
            return;
        }
    } else {
        $isToAuto = false;
        $sql = "SELECT id FROM game28 WHERE kj = 0 and id = '{$No}' ";
        $query = $db->query($sql);
        if ($rs = $db->fetch_array($query)) {
            $No = $rs["id"];
        } else {
            $arrReturn['msg'] = "{$No} had opened(pk)";
            $arrReturn['log'] .= LogFormat("{$No} had opened(pk)");
            return;
        }
    }
    $arrReturn['no'] = $No;
    $strkjNum = GetGameResult($No);
    $kjnum_array = explode("|", $strkjNum);

    if (count($kjnum_array) == 20) //取到了
    {
        //排序
        sort($kjnum_array, SORT_NUMERIC);
        //更新开奖状态
        $sql = "update game_result set isopen = 1,opentime = now() where gametype = 'gamebj' and gameno = '{$No}'";
        //$db->query($sql);

        $arrReturn['log'] .= LogFormat("open result string:" . $strkjNum . " (bj)");
        $arrReturn['log'] .= LogFormat('begin open time:' . date('Y-m-d H:i:s'));
        //开奖蛋蛋28
        $zjh_a = $kjnum_array[0] + $kjnum_array[1] + $kjnum_array[2] + $kjnum_array[3] + $kjnum_array[4] + $kjnum_array[5];
        $zjh_b = $kjnum_array[6] + $kjnum_array[7] + $kjnum_array[8] + $kjnum_array[9] + $kjnum_array[10] + $kjnum_array[11];
        $zjh_c = $kjnum_array[12] + $kjnum_array[13] + $kjnum_array[14] + $kjnum_array[15] + $kjnum_array[16] + $kjnum_array[17];
        $zj_a = substr($zjh_a, -1);
        $zj_b = substr($zjh_b, -1);
        $zj_c = substr($zjh_c, -1);
        $zj_result = $zj_a + $zj_b + $zj_c;
        //$sql = "call web_kj_game28({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
        //$arr = $db->Mysqli_Multi_Query($sql);
        /*--------pro-------------------------*/
        echo 'start';
        $sql = "CALL web_gameno_addpatch('gamebj',3,0,10);";
        $res = $db->query($sql);
        var_dump($res);
        //$arr=kj_28($No, $zj_a, $zj_b, $zj_c, $zj_result, $strkjNum);


        /*
        CREATE DEFINER=`root`@`localhost` PROCEDURE `web_kj_game28`(
            p_No	INT,
                p_numa	INT,
                p_numb	INT,
                p_numc	INT,
                p_kjnum	INT,
                p_gfNo	VARCHAR(500) CHARACTER SET gbk
            )
            SQL SECURITY INVOKER
        BEGIN
        -- ************************************************************************************
            -- 名称:开奖
            -- p_No 期号
            -- p_numa 	号码1
            -- p_numb 	号码2
            -- p_numc 	号码3
            -- p_kjnum	开奖号码
            -- p_gfNo 	官方号码
            -- 返回，0：成功，1:该期已开过奖，2：游戏已停止，3,取中奖赔率错误，99：系统错误
            -- ************************************************************************************
            DECLARE v_GameType INT DEFAULT 3; -- 游戏标识
            DECLARE v_GameStep INT DEFAULT 1; -- 开奖最小号码离1步长 x=1-首个开始号
            DECLARE v_gameSamples INT; -- 抽税千分比
            DECLARE v_gameTax BIGINT DEFAULT 0; -- 游戏抽税
            DECLARE v_tzPoints BIGINT; -- 投注总额
            DECLARE v_kjPoints BIGINT; -- 开奖总额
            DECLARE v_RewardsumPoints BIGINT; -- 中奖总额
            DECLARE v_RewardNum	INT; -- 中奖号码
            DECLARE v_RewardOdds DECIMAL(20,4); -- 中奖赔率
            DECLARE v_Odds_str VARCHAR(20) CHARACTER SET gbk; -- 中奖赔率
            DECLARE v_RewardrCount INT; -- 中奖人数
            DECLARE v_usrtzPoints	BIGINT; -- 用户投注总额
            DECLARE v_UserWin	BIGINT; -- 用户输赢
            DECLARE v_ReardOdds_str VARCHAR(2000) CHARACTER SET gbk; -- 中奖赔率字符串，|分隔
            DECLARE v_result INT DEFAULT 0;
            DECLARE v_retmsg VARCHAR(200) CHARACTER SET gbk DEFAULT 'ok'; -- 错误信息
            DECLARE err INT DEFAULT 0;
            DECLARE v_opentime DATETIME;
            DECLARE v_ingame_num INT DEFAULT 0; -- 在游戏标识
            DECLARE v_ChangeRewardCount INT DEFAULT 0; -- 更新中奖记录数

            DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET err=1;

            START TRANSACTION;
            LABEL_EXIT:BEGIN
                SELECT tzpoints,DATE_FORMAT(kgtime,'%Y-%m-%d') FROM game28 WHERE id = p_No AND kj = 0
                    INTO v_tzPoints,v_opentime;
                IF v_tzPoints IS NULL THEN
                    SELECT 1 INTO v_result;
                    SET v_retmsg = '该期已开奖';
                    LEAVE LABEL_EXIT;
                END IF;

                IF v_tzPoints = 0 AND EXISTS(SELECT 1 FROM sys_config WHERE fldVar = 'game_open_flag' AND fldValue = "1") THEN
                    SET v_result = 2;
                    SET v_retmsg = '游戏已停止';
                    LEAVE LABEL_EXIT;
                END IF;
                -- 抽税
                SELECT game_go_samples FROM game_config WHERE game_type = v_GameType
                    INTO v_gameSamples;
                IF v_gameSamples = 0 THEN
                    SET v_kjPoints = v_tzPoints;
                ELSE
                    SET v_kjPoints = FLOOR(v_tzPoints * (10000 - v_gameSamples) / 10000);
                END IF;
                -- 取得最新赔率
                SELECT GROUP_CONCAT(TRUNCATE(odds,4) SEPARATOR '|')
                FROM
                (
                    SELECT odds FROM
            (
                SELECT num,0.00 AS odds
                        FROM gameodds WHERE game_type = 'game28'
            AND num NOT IN(SELECT DISTINCT tznum FROM game28_kg_users_tz WHERE NO = p_No)
                        UNION
                        SELECT tznum AS num,TRUNCATE(v_kjPoints/SUM(tzpoints),4) AS odds
                        FROM game28_kg_users_tz
                        WHERE NO = p_No GROUP BY tznum
                    ) b
                    ORDER BY num
                ) a
                INTO v_ReardOdds_str;

                -- 中奖赔率
                SET v_RewardNum = p_kjnum;
                SELECT Get_StrArrayStrOfIndex(v_ReardOdds_str,'|',v_RewardNum+v_GameStep) INTO v_Odds_str;
                IF v_Odds_str = '' THEN
                    SELECT 3 INTO v_result; -- 取中奖赔率错误
                    SET v_retmsg = '取中奖赔率错误';
                    LEAVE LABEL_EXIT;
                END IF;
                SET v_RewardOdds = v_Odds_str * 1.00;
                /*
                insert into gameall_reward_num(uid,gametype,`NO`,tznum,tzpoints,`time`,reward_odds,hdpoints)
                    select uid,v_GameType,`NO`,tznum,tzpoints,`time`,v_RewardOdds,FLOOR(tzpoints * v_RewardOdds)
                    from game28_kg_users_tz
                    where `No` = p_No AND tznum = v_RewardNum and usertype = 0;
                */
        /*-- 更新中奖
        UPDATE game28_kg_users_tz SET hdpoints = FLOOR(tzpoints * v_RewardOdds)
            WHERE `No` = p_No AND tznum = v_RewardNum;
        SET v_ChangeRewardCount = ROW_COUNT();
        -- 取得中奖人数和金额
        SELECT COUNT(uid),IFNULL(SUM(hdpoints),0) FROM game28_kg_users_tz WHERE `No` = p_No AND tznum = v_RewardNum
            INTO v_RewardrCount,v_RewardsumPoints;
        IF v_ChangeRewardCount > 0 AND v_RewardsumPoints = 0 THEN
        -- 记录日志
            INSERT INTO system_msg(msg_type,msg_content,msg_time)
                VALUES('全压无中奖',CONCAT('game28第',p_No,'期,能更新中奖但更新后中奖为0'),NOW());
            -- 设置重开奖
            UPDATE game_result SET isopen = 0 WHERE gameno = p_No;
            SELECT 4 INTO v_result; -- 可能锁表
            SET v_retmsg = '无法更新中奖，可能被锁表了';
            LEAVE LABEL_EXIT;
        END IF;
        /*
        -- 锁表
        SELECT id FROM users WHERE id IN(
            SELECT uid FROM game28_kg_users_tz WHERE `No` = p_No AND tznum = v_RewardNum AND usertype = 0
        ) FOR UPDATE;

        -- 记录分明细
        INSERT INTO user_score_changelog(gametype,gameno,uid,points,back,lock_points,experience,change_points,thetime,remark)
            SELECT v_GameType,p_No,id,points,back,lock_points,experience,0,NOW(),'开奖前'
            FROM users WHERE id IN(SELECT uid FROM game28_kg_users_tz WHERE `No` = p_No AND usertype = 0 GROUP BY uid);
        */
        /*-- 批量更新中奖
        UPDATE users AS a,
            (
            SELECT uid,hdpoints
                FROM game28_kg_users_tz WHERE `No` = p_No AND tznum = v_RewardNum AND usertype = 0
            ) AS b
        SET a.points = a.points + b.hdpoints
        WHERE a.id = b.uid AND a.usertype = 0;

        UPDATE game_static AS a,
            (
            SELECT uid,hdpoints
                FROM game28_kg_users_tz WHERE `No` = p_No AND tznum = v_RewardNum AND usertype = 0
            ) AS b
        SET a.points = a.points + b.hdpoints
        WHERE a.uid = b.uid AND a.typeid = v_GameType;

        --  每天实时输赢
        UPDATE game_day_static AS a,
        (
        SELECT IFNULL(SUM(hdpoints),0) AS sumhdpoints,IFNULL(SUM(tzpoints),0) AS sumtzpoints,uid
            FROM  game28_kg_users_tz WHERE `No` = p_No AND usertype = 0 GROUP BY uid
        ) AS b
        SET a.points = a.points + b.sumhdpoints - b.sumtzpoints
        WHERE a.uid = b.uid AND a.`time`= v_opentime AND a.kindid=v_GameType;

        SELECT IFNULL(SUM(hdpoints),0) AS sumhdpoints,IFNULL(SUM(tzpoints),0) AS sumtzpoints
            FROM game28_kg_users_tz
            WHERE `NO` = p_No AND usertype = 0
            INTO v_UserWin,v_usrtzPoints;

        INSERT INTO game28_users_tz(uid,`NO`,tznum,tzpoints,zjpoints,`TIME`,points,hdpoints)
            SELECT uid,`NO`,GROUP_CONCAT(tznum ORDER BY id ASC SEPARATOR '|'),
                GROUP_CONCAT(tzpoints ORDER BY id ASC SEPARATOR '|'),
                GROUP_CONCAT(hdpoints ORDER BY id ASC SEPARATOR '|'),
                `TIME`,SUM(tzpoints),SUM(hdpoints)
            FROM game28_kg_users_tz
            WHERE `NO` = p_No AND usertype = 0   GROUP BY uid;

        -- 更新冻结/游戏状态
        SET v_ingame_num = POWER(2,v_GameType);
        UPDATE users AS a,
        (
        SELECT uid,SUM(tzpoints) AS points FROM game28_kg_users_tz WHERE `NO` = p_No AND usertype = 0 GROUP BY uid
        ) b
        SET a.lock_points = a.lock_points - b.points,a.ingame = (a.ingame ^ v_ingame_num)
        WHERE a.id = b.uid AND a.usertype = 0;
        -- 刷新在线状态
        UPDATE users AS a,
        (
        SELECT uid FROM game28_kg_users_tz WHERE `NO` > p_NO AND usertype = 0 GROUP BY uid
        ) b
        SET a.ingame = (a.ingame | v_ingame_num)
        WHERE a.id = b.uid AND a.usertype = 0;

        -- 游戏扣税
        SET v_gameTax =  CEIL(v_usrtzPoints * v_gameSamples/10000);

        -- 记录中央银行
        -- SELECT score FROM centerbank WHERE bankIdx IN(14,15) FOR UPDATE;
    IF v_gameTax > 0 THEN
            UPDATE centerbank SET score = score + v_gameTax WHERE bankIdx = 14;
        END IF;
        UPDATE centerbank SET score = score - (v_UserWin - v_usrtzPoints) - v_gameTax  WHERE bankIdx = 15;
        -- 记录每天统计
        IF EXISTS(SELECT 1 FROM webtj WHERE `time` = CURDATE()) THEN
            UPDATE webtj SET game28 = game28 + (v_UserWin - v_usrtzPoints),gametax = gametax + v_gameTax
                WHERE `time` = CURDATE();
        ELSE
            INSERT INTO webtj(`time`,game28,gametax) VALUES(CURDATE(),v_UserWin - v_usrtzPoints,v_gameTax);
        END IF;

        UPDATE game28 SET kgjg = CONCAT(p_numa,'|',p_numb,'|',p_numc,'|',v_RewardNum),take_time_remark = CONCAT(v_RewardOdds,'|',v_ChangeRewardCount,'|',v_RewardsumPoints),
            kj = 1,zjrnum = v_RewardrCount,zjpl = v_ReardOdds_str,kgNo = p_gfNo,game_tax = v_gameTax,user_tzpoints = v_usrtzPoints,user_winpoints = v_UserWin
            WHERE id = p_No;
        -- 记录分明细
        INSERT INTO user_score_changelog(gametype,gameno,uid,points,back,lock_points,experience,change_points,thetime,remark)
            SELECT v_GameType,p_No,a.id,a.points,a.back,a.lock_points,a.experience,b.sumhdpoints,NOW(),'开奖后'
            FROM users a,
            (
            SELECT uid,SUM(hdpoints) AS sumhdpoints FROM game28_kg_users_tz WHERE `No` = p_No AND usertype = 0 GROUP BY uid
            ) b
            WHERE a.id = b.uid AND a.usertype = 0;
        -- 删除预投注记录
        DELETE FROM game28_kg_users_tz WHERE `No` = p_No;

    END LABEL_EXIT;

    IF err=1  THEN
        SET v_result = 99;
        SET v_retmsg = '数据库错误!';
    END IF;

    IF v_result = 0 THEN
        COMMIT;
    ELSE
        ROLLBACK;
        IF err = 1 THEN
        -- 让重新开奖
            UPDATE game_result SET isopen = 0 WHERE gameno = p_No;
            -- 记录日志
            INSERT INTO system_msg(msg_type,msg_content,msg_time)
                VALUES('开奖错误',CONCAT('game28第',p_No,'期由于数据库错误回滚，自动重新开奖'),NOW());
        END IF;
    END IF;
    -- 生成新期号
    CALL web_gameno_addpatch('gamebj',v_GameType,0,10);
    SELECT v_result AS result,v_retmsg AS msg;
END$$

DELIMITER ;*/
        //--------------------------------------


        $arrRet['code'] = $arr[0][0]["result"];
        $arrRet['msg'] = $arr[0][0]["msg"];
        $strlog = "game28 " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})" . " (bj)";
        $arrReturn['log'] .= LogFormat($strlog);

        //开奖蛋蛋36
        $zjh_a = $kjnum_array[0] + $kjnum_array[1] + $kjnum_array[2] + $kjnum_array[3] + $kjnum_array[4] + $kjnum_array[5];
        $zjh_b = $kjnum_array[6] + $kjnum_array[7] + $kjnum_array[8] + $kjnum_array[9] + $kjnum_array[10] + $kjnum_array[11];
        $zjh_c = $kjnum_array[12] + $kjnum_array[13] + $kjnum_array[14] + $kjnum_array[15] + $kjnum_array[16] + $kjnum_array[17];
        $zj_a = substr($zjh_a, -1);
        $zj_b = substr($zjh_b, -1);
        $zj_c = substr($zjh_c, -1);
        $zj_result = GetGame36Result($zj_a, $zj_b, $zj_c);
        $sql = "call web_kj_game36({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
        $arr = $db->Mysqli_Multi_Query($sql);
        $arrRet['code'] = $arr[0][0]["result"];
        $arrRet['msg'] = $arr[0][0]["msg"];
        $strlog = "game36 " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})" . " (bj)";
        $arrReturn['log'] .= LogFormat($strlog);
        //开奖北京28
        $zjh_a = $kjnum_array[1] + $kjnum_array[4] + $kjnum_array[7] + $kjnum_array[10] + $kjnum_array[13] + $kjnum_array[16];
        $zjh_b = $kjnum_array[2] + $kjnum_array[5] + $kjnum_array[8] + $kjnum_array[11] + $kjnum_array[14] + $kjnum_array[17];
        $zjh_c = $kjnum_array[3] + $kjnum_array[6] + $kjnum_array[9] + $kjnum_array[12] + $kjnum_array[15] + $kjnum_array[18];
        $zj_a = substr($zjh_a, -1);
        $zj_b = substr($zjh_b, -1);
        $zj_c = substr($zjh_c, -1);
        $zj_result = $zj_a + $zj_b + $zj_c;
        $sql = "call web_kj_gameself28({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
        $arr = $db->Mysqli_Multi_Query($sql);
        $arrRet['code'] = $arr[0][0]["result"];
        $arrRet['msg'] = $arr[0][0]["msg"];
        $strlog = "gameself28 " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})" . " (bj)";
        $arrReturn['log'] .= LogFormat($strlog);

        //开奖北京36
        $zjh_a = $kjnum_array[1] + $kjnum_array[4] + $kjnum_array[7] + $kjnum_array[10] + $kjnum_array[13] + $kjnum_array[16];
        $zjh_b = $kjnum_array[2] + $kjnum_array[5] + $kjnum_array[8] + $kjnum_array[11] + $kjnum_array[14] + $kjnum_array[17];
        $zjh_c = $kjnum_array[3] + $kjnum_array[6] + $kjnum_array[9] + $kjnum_array[12] + $kjnum_array[15] + $kjnum_array[18];
        $zj_a = substr($zjh_a, -1);
        $zj_b = substr($zjh_b, -1);
        $zj_c = substr($zjh_c, -1);
        $zj_result = GetGame36Result($zj_a, $zj_b, $zj_c);
        $sql = "call web_kj_gamebj36({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
        $arr = $db->Mysqli_Multi_Query($sql);
        $arrRet['code'] = $arr[0][0]["result"];
        $arrRet['msg'] = $arr[0][0]["msg"];
        $strlog = "gamebj36 " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})" . " (bj)";
        $arrReturn['log'] .= LogFormat($strlog);

        //开奖北京16
        $zjh_a = $kjnum_array[0] + $kjnum_array[3] + $kjnum_array[6] + $kjnum_array[9] + $kjnum_array[12] + $kjnum_array[15];
        $zj_a = ($zjh_a % 6) + 1;
        $zjh_b = $kjnum_array[1] + $kjnum_array[4] + $kjnum_array[7] + $kjnum_array[10] + $kjnum_array[13] + $kjnum_array[16];
        $zj_b = ($zjh_b % 6) + 1;
        $zjh_c = $kjnum_array[2] + $kjnum_array[5] + $kjnum_array[8] + $kjnum_array[11] + $kjnum_array[14] + $kjnum_array[17];
        $zj_c = ($zjh_c % 6) + 1;
        $zj_result = $zj_a + $zj_b + $zj_c;
        $sql = "call web_kj_gamebj16({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
        $arr = $db->Mysqli_Multi_Query($sql);
        $arrRet['code'] = $arr[0][0]["result"];
        $arrRet['msg'] = $arr[0][0]["msg"];
        $strlog = "gamebj16 " . $No . " result is:{$arrRet['msg']}({$arrRet['code']})" . " (bj)";
        $arrReturn['log'] .= LogFormat($strlog);
        $arrReturn['log'] .= LogFormat('end open time:' . date('Y-m-d H:i:s') . " (bj)");
    } else //取不到结果
    {
        $arrReturn['code'] = 'noreward';
        $arrReturn['msg'] = "no open {$No} result(bj)";
        $arrReturn['log'] = LogFormat("no open {$No} result!(bj)");
        return;
    }
    if ($isToAuto) {
        //给最新一盘自动投注
        $NextNo = $No + 1;
        $randScond = rand(3, 5);
        $sql = "SELECT id,DATE_ADD(NOW(),INTERVAL {$randScond} SECOND) nowtime FROM game28 WHERE kj = 0 and id={$NextNo} limit 1";
        $query = $db->query($sql);
        if ($rs = $db->fetch_array($query)) {
            $arrReturn['nextid'] = $rs['id'];
            $arrReturn['nexttime'] = $rs['nowtime'];
            //自动投注
            AutoPress($arrReturn, $No, $NextNo);
        }
    }


}

function AutoPress(&$arrReturn, $No, $NextNo)
{
    global $db;
    //蛋蛋28自动投注
    $sql = "call web_tz_game28_auto_new({$No},{$NextNo})";
    $arrT = $db->Mysqli_Multi_Query($sql);
    $strlog = "game28 " . $arrRet['nextid'] . " auto press(" . $arrT[0][0]["result"] . ")" . " (bj)";
    $arrReturn['log'] .= LogFormat($strlog);
    //蛋蛋36自动投注
    $sql = "call web_tz_game36_auto_new({$No},{$NextNo})";
    $arrT = $db->Mysqli_Multi_Query($sql);
    $strlog = "game36 " . $arrRet['nextid'] . " auto press(" . $arrT[0][0]["result"] . ")" . " (bj)";
    $arrReturn['log'] .= LogFormat($strlog);
    //北京28自动投注
    $sql = "call web_tz_gameself28_auto_new({$No},{$NextNo})";
    $arrT = $db->Mysqli_Multi_Query($sql);
    $strlog = "gameself28 " . $arrRet['nextid'] . " auto press(" . $arrT[0][0]["result"] . ")" . " (bj)";
    $arrReturn['log'] .= LogFormat($strlog);
    //北京36自动投注
    $sql = "call web_tz_gamebj36_auto_new({$No},{$NextNo})";
    $arrT = $db->Mysqli_Multi_Query($sql);
    $strlog = "game36 " . $arrRet['nextid'] . " auto press(" . $arrT[0][0]["result"] . ")" . " (bj)";
    $arrReturn['log'] .= LogFormat($strlog);
    //北京16自动投注
    $sql = "call web_tz_gamebj16_auto_new({$No},{$NextNo})";
    $arrT = $db->Mysqli_Multi_Query($sql);
    $strlog = "gamebj16 " . $arrRet['nextid'] . " auto press(" . $arrT[0][0]["result"] . ")" . " (bj)";
    $arrReturn['log'] .= LogFormat($strlog);
    $arrReturn['log'] .= LogFormat('end autopress time:' . date('Y-m-d H:i:s') . " (bj)");
}

function GetGame36Result($a, $b, $c)
{
    $arrNum = array($a, $b, $c);
    sort($arrNum);
    if ($arrNum[0] == $arrNum[2]) //豹子
        return 1;
    if ($arrNum[0] == $arrNum[1] || $arrNum[1] == $arrNum[2]) //对子
        return 2;
    if ($arrNum[0] == 0 && $arrNum[1] == 1 && $arrNum[2] == 9)//顺子特例
        return 3;
    if ($arrNum[1] - $arrNum[0] == 1 && $arrNum[2] - $arrNum[1] == 1) //顺子
        return 3;
    if ($arrNum[0] == 0 && $arrNum[2] == 9)//半顺特例
        return 4;
    if ($arrNum[1] - $arrNum[0] == 1 || $arrNum[2] - $arrNum[1] == 1) //半顺
        return 4;
    return 5; //杂
}

function GetGameResult($theNo)
{
    global $db;
    $ret = "";

    $sql = "select gameresult from game_result where gametype='gamebj' and gameno = '{$theNo}' and isopen = 0";
    $query = $db->query($sql);
    if ($rs = $db->fetch_array($query)) {
        $ret = $rs["gameresult"];
    }

    return $ret;
}


error_reporting(0);
set_time_limit(200);
include_once("inc/conn.php");
include_once("inc/function.php");
include_once("heheadmin/inc/config.php");
die('---');
if ($_GET['key'] == "kj_beijingtype_result") {
    $arrRet = array('code' => 'ok', //
        'no' => '',
        'msg' => '', //错误信息 -1:不在开奖时间内，0：开奖成功，1：该期已开过奖，2：取中奖赔率错误，99：系统错误
        'log' => '',
        'nextid' => '', //下一盘id
        'nexttime' => '' //下一篇开奖时间
    );
    addpatch('gamebj', 3, 0, 10);
    //$res=$db->query($sql);
    //var_dump($res);
    game_go($arrRet);
    if ($arrRet['nextid'] == '') {
        $RandSecond = rand(3, 5);
        $sql = "select date_add(NOW(),INTERVAL {$RandSecond} SECOND) nowtime,id from game28 where kgtime > now() and kj = 0 order by id limit 1";
        $query = $db->query($sql);
        if ($rs = $db->fetch_array($query)) {
            $arrRet['nextid'] = $rs['id'];
            $arrRet['nexttime'] = date('Y-m-d H:i:s', strtotime($rs["nowtime"]));
        } else {
            $arrRet['nextid'] = '0';
            $arrRet['nexttime'] = date('Y-m-d H:i:s', strtotime("+{$RandSecond} second"));
        }
    }
    //返回
    echo "^" . json_encode($arrRet);
}
function kj_28($No, $zj_a, $zj_b, $zj_c, $zj_result, $strkjNum)
{
    global $db;
    $p_No = $No;
    $p_numb = $zj_a;
    $p_numb = $zj_b;
    $p_numc = $zj_c;
    $p_kjnum = $zj_result;
    $p_gfNo = $strkjNum;

    $v_GameStep = 1;
    $v_GameType = 3;// -- 游戏标识
    $v_GameStep = 1;// -- 开奖最小号码离1步长 x=1-首个开始号
    $v_gameSamples = 0;// -- 抽税千分比
    $v_gameTax = 0;// -- 游戏抽税
    $v_tzPoints = 0;// -- 投注总额
    $v_kjPoints = 0; //-- 开奖总额
    $v_RewardsumPoints = 0; //-- 中奖总额
    $v_RewardNum = 0; //-- 中奖号码
    $v_RewardOdds = 0;//DECIMAL(20,4); //-- 中奖赔率
    $v_Odds_str = '';// VARCHAR(20) CHARACTER SET gbk; //-- 中奖赔率
    $v_RewardrCount = 0;//INT; //-- 中奖人数
    $v_usrtzPoints = 0;//	BIGINT; //-- 用户投注总额
    $v_UserWin = 0;//	BIGINT; //-- 用户输赢
    $v_ReardOdds_str = '';// VARCHAR(2000) CHARACTER SET gbk; //-- 中奖赔率字符串，|分隔
    $v_result = 0;//INT DEFAULT 0;
    $v_retmsg = '';// VARCHAR(200) CHARACTER SET gbk DEFAULT 'ok'; //-- 错误信息
    $err = 0;// INT DEFAULT 0;
    $v_opentime = '';// DATETIME;
    $v_ingame_num = 0;// INT DEFAULT 0; //-- 在游戏标识
    $v_ChangeRewardCount = 0;// INT DEFAULT 0; //-- 更新中奖记录数

    $sql = 'SELECT tzpoints,DATE_FORMAT(kgtime,\'%Y-%m-%d\') as v_opentime FROM game28 WHERE id = ' . $p_No . ' AND kj = 0;';
    echo $sql;
    $res = $db->fetch_first($sql);
    $v_tzPoints = $res['tzpoints'];
    $v_opentime = $res['v_opentime'];
    var_dump($res);
    if ($res['tzpoints'] == null) {
        echo '游戏已开奖!';
        return array(array('result' => 1, 'msg' => '游戏已开奖'));
    }
    if ($res['tzpoints'] == 0) {
        $sql = 'SELECT 1 FROM sys_config WHERE fldVar = \'game_open_flag\' AND fldValue = "1"
';
        $res = $db->fetch_first($sql);
        var_dump($res);
        if ($res) {
            echo '游戏已停止';
            return array(array('result' => 2, 'msg' => '游戏已停止'));
        }
    }


    //-- 抽税
    $sql = "SELECT game_go_samples FROM game_config WHERE game_type = 3";
    $res = $db->fetch_first($sql);
    $v_gameSamples = $res['game_go_samples'];
    if ($v_gameSamples == 0) {
        $v_kjPoints = $v_gameSamples;
    } else {
        $v_kjPoints = floatval($v_tzPoints * (10000 - $v_gameSamples) / 10000);
    }

    //-- 取得最新赔率
    $sql = "SELECT GROUP_CONCAT(TRUNCATE(odds,4) SEPARATOR '|') as v_ReardOdds_str
		FROM
        (
            SELECT odds FROM
    (
        SELECT num,0.00 AS odds
				FROM gameodds WHERE game_type = 'game28'
    AND num NOT IN(SELECT DISTINCT tznum FROM game28_kg_users_tz WHERE NO = $p_No)
				UNION
				SELECT tznum AS num,TRUNCATE($v_kjPoints/SUM(tzpoints),4) AS odds 
				FROM game28_kg_users_tz 
				WHERE NO = $p_No GROUP BY tznum
			) b 
			ORDER BY num
		) a";
    $res = $db->fetch_first($sql);
    echo '---------v_ReardOdds-str-----' . "\r\n";
    var_dump($res);
    echo '---------v_ReardOdds-str-----' . "\r\n";
    $v_ReardOdds_str = $res['v_ReardOdds_str'];


    //-- 中奖赔率
    $v_RewardNum = $p_kjnum;
    $sql = "SELECT Get_StrArrayStrOfIndex($v_ReardOdds_str,'|',$v_RewardNum+$v_GameStep) ";
    $res = $db->fetch_first($sql);
    echo '---------v_Odds_str-----' . "\r\n";
    var_dump($res);
    echo '---------v_Odds_str-----' . "\r\n";
    $v_Odds_str = $res['v_Odds_str'];
    if ($v_Odds_str == '') {
        $v_result = 3;
        $v_retmsg = '取中奖赔率错误';
    }
    $v_RewardOdds = $v_Odds_str * 1.00;
    //-- 更新中奖
    $sql = "UPDATE game28_kg_users_tz SET hdpoints = FLOOR(tzpoints * $v_RewardOdds)
			WHERE `No` = $p_No AND tznum = $v_RewardNum";
    $res = $db->query($sql);
    $v_ChangeRewardCount = "select ROW_COUNT()";
    $res = $db->fetch_first($sql);
    echo '---------$v_ChangeRewardCount---影响的行数--' . "\r\n";
    var_dump($res);
    echo '---------$v_ChangeRewardCount-----' . "\r\n";
    //-- 取得中奖人数和金额
    $sql = "SELECT COUNT(uid) as v_RewardrCount,IFNULL(SUM(hdpoints),0) as v_RewardsumPoints FROM game28_kg_users_tz WHERE `No` = $p_No AND tznum = $v_RewardNum";
    $res = $db->fetch_first($sql);
    $v_RewardrCount = $res['v_RewardrCount'];
    $v_RewardsumPoints = $res['v_RewardsumPoints'];
    echo '---------v_RewardrCount---取得中奖人数和金额--' . "\r\n";
    var_dump($res);
    echo '---------v_RewardrCount-----' . "\r\n";

    if ($v_ChangeRewardCount > 0 AND $v_RewardsumPoints = 0) {
        //       -- 记录日志
        $sql = "INSERT INTO system_msg(msg_type, msg_content, msg_time)
				VALUES('全压无中奖', CONCAT('game28第', $p_No, '期,能更新中奖但更新后中奖为0'), NOW())";
        $db->query($sql);
        //--设置重开奖
        $sql = "UPDATE game_result SET isopen = 0 WHERE gameno = $p_No";
        $res = $db->query($sql);
        //SELECT 4 INTO v_result; --可能锁表
        //SET v_retmsg = '无法更新中奖，可能被锁表了';
        //LEAVE LABEL_EXIT;
    }
    //-- 批量更新中奖
    $sql = "UPDATE users AS a,
			(
            SELECT uid,hdpoints 
				FROM game28_kg_users_tz WHERE `No` = $p_No AND tznum = $v_RewardNum AND usertype = 0
			) AS b
		SET a.points = a.points + b.hdpoints
		WHERE a.id = b.uid AND a.usertype = 0";
    $db->query($sql);

    $sql = "UPDATE game_static AS a,
			(
            SELECT uid,hdpoints 
				FROM game28_kg_users_tz WHERE `No` = $p_No AND tznum = $v_RewardNum AND usertype = 0 
			) AS b
		SET a.points = a.points + b.hdpoints
		WHERE a.uid = b.uid AND a.typeid = $v_GameType";
    $db->query($sql);
    //--  每天实时输赢
    $sql = "UPDATE game_day_static AS a,
		(
        SELECT IFNULL(SUM(hdpoints),0) AS sumhdpoints,IFNULL(SUM(tzpoints),0) AS sumtzpoints,uid
			FROM  game28_kg_users_tz WHERE `No` = $p_No AND usertype = 0 GROUP BY uid
		) AS b
		SET a.points = a.points + b.sumhdpoints - b.sumtzpoints
		WHERE a.uid = b.uid AND a.`time`= $v_opentime AND a.kindid=$v_GameType";
    $db->query($sql);
    $sql = "SELECT IFNULL(SUM(hdpoints),0) AS sumhdpoints,IFNULL(SUM(tzpoints),0) AS sumtzpoints 
			FROM game28_kg_users_tz
			WHERE `NO` = p_No AND usertype = 0
			INTO v_UserWin,v_usrtzPoints";
    $db->fetch_array($sql);
    $sql = "INSERT INTO game28_users_tz(uid,`NO`,tznum,tzpoints,zjpoints,`TIME`,points,hdpoints) 
			SELECT uid,`NO`,GROUP_CONCAT(tznum ORDER BY id ASC SEPARATOR '|'),
				GROUP_CONCAT(tzpoints ORDER BY id ASC SEPARATOR '|'),
				GROUP_CONCAT(hdpoints ORDER BY id ASC SEPARATOR '|'),
				`TIME`,SUM(tzpoints),SUM(hdpoints) 
			FROM game28_kg_users_tz 
			WHERE `NO` = p_No AND usertype = 0   GROUP BY uid";

    //-- 更新冻结/游戏状态
    $v_ingame_num = pow(2, $v_GameType);
    $sql = "UPDATE users AS a,
		(
        SELECT uid,SUM(tzpoints) AS points FROM game28_kg_users_tz WHERE `NO` = p_No AND usertype = 0 GROUP BY uid
		) b
		SET a.lock_points = a.lock_points - b.points,a.ingame = (a.ingame ^ v_ingame_num)
		WHERE a.id = b.uid AND a.usertype = 0";

    //-- 刷新在线状态
    $sql = "UPDATE users AS a,
		(
        SELECT uid FROM game28_kg_users_tz WHERE `NO` > p_NO AND usertype = 0 GROUP BY uid
		) b
		SET a.ingame = (a.ingame | v_ingame_num)
		WHERE a.id = b.uid AND a.usertype = 0";

    //-- 游戏扣税
    $v_gameTax = ceil($v_usrtzPoints * $v_gameSamples / 10000);

    //-- 记录中央银行
    if ($v_gameTax > 0) {
        $sql = "UPDATE centerbank SET score = score + v_gameTax WHERE bankIdx = 14;";
    }
    $sql = "UPDATE centerbank SET score = score - (v_UserWin - v_usrtzPoints) - v_gameTax  WHERE bankIdx = 15;";

    //-- 记录每天统计
    /*IF EXISTS(SELECT 1 FROM webtj WHERE `time` = CURDATE()) THEN
        UPDATE webtj SET game28 = game28 + (v_UserWin - v_usrtzPoints),gametax = gametax + v_gameTax
            WHERE `time` = CURDATE();
    ELSE
        INSERT INTO webtj(`time`,game28,gametax) VALUES(CURDATE(),v_UserWin - v_usrtzPoints,v_gameTax);
    END IF;*/

    $sql = "UPDATE game28 SET kgjg = CONCAT($zj_a,'|',$zj_b,'|',$zj_c,'|',$v_RewardNum),take_time_remark = CONCAT($v_RewardOdds,'|',$v_ChangeRewardCount,'|',$v_RewardsumPoints),
			kj = 1,zjrnum = $v_RewardrCount,zjpl = $v_ReardOdds_str,kgNo = $p_gfNo,game_tax = $v_gameTax,user_tzpoints = $v_usrtzPoints,user_winpoints = $v_UserWin
			WHERE id = $p_No";
    $db->query($sql);
//		-- 记录分明细
    /*$sql="INSERT INTO user_score_changelog(gametype,gameno,uid,points,back,lock_points,experience,change_points,thetime,remark)
        SELECT v_GameType,p_No,a.id,a.points,a.back,a.lock_points,a.experience,b.sumhdpoints,NOW(),'开奖后'
        FROM users a,
        (
        SELECT uid,SUM(hdpoints) AS sumhdpoints FROM game28_kg_users_tz WHERE `No` = p_No AND usertype = 0 GROUP BY uid
        ) b
        WHERE a.id = b.uid AND a.usertype = 0;*/
    //-- 删除预投注记录
    //DELETE FROM game28_kg_users_tz WHERE `No` = p_No";

}

function addpatch($p_gamekind, $p_gametype, $p_specifyno, $p_reccount)
{
    global $db;
    /*-- ************************************************************************************
	-- 名称:生成最新期号
    -- p_gamekind 	指定期号，0为系统自动
    -- p_gametype	游戏标识ID
    -- p_specifyno 	指定开始期号，0为系统取
    -- p_reccount 	期数
    -- 返回，0：成功，1:无法取到待开奖期号，99：系统错误
    -- *************************************************************************************/
    $v_tablename = '';// VARCHAR(100); -- 游戏表名
    $v_table_users_tz = '';// VARCHAR(100); -- 记录表名
    $v_no = 0;// INT DEFAULT 0; -- 期号
    $v_interval_second = 0;// INT; -- 两期间隔秒数
    $v_begin_time = 0;// TIME; -- 开始时间
    $v_end_time = 0;// TIME; -- 结束时间
    $v_no_time = 0;// DATETIME; -- 期号时间
    $v_hadno_count = 0;// INT DEFAULT 0; -- 目前已经有的期号
    $v_odds = '';// VARCHAR(1000) CHARACTER SET gbk; -- 标准赔率
    $v_overtime = '';// DATETIME; -- 过期时间
    $v_i = '';// INT DEFAULT 0;
    $v_ret = '';// INT DEFAULT 0;
    $err = '';// INT DEFAULT 0;


    //-- 取表名
    $sql = "SELECT game_table_prefix FROM game_config WHERE game_type = $p_gametype LIMIT 1";
    $res = $db->fetch_first($sql);
    $v_tablename = $res['game_table_prefix'];
    var_dump($res);
    var_dump($p_specifyno);
    var_dump('$p_specifyno');
    //	-- 判断是否需要加新记录
    $sql = "SELECT count(*) as reccount FROM $v_tablename WHERE kj = 0 and kgtime > DATE_ADD(NOW(),INTERVAL -10 MINUTE )";
    $res = $db->fetch_first($sql);
    $v_hadno_count = $v_reccount = $res['reccount'];
    var_dump($v_hadno_count);
    var_dump($res);
    if ($v_hadno_count >= $p_reccount) {
        echo 'chu cuo';
        //return ;
    }
    //	-- 删除过期日志
    if (date('H', time()) == 9) {
        /*DELETE FROM game_result WHERE isopen = 1 AND opentime < DATE_ADD(NOW(), INTERVAL - 1 DAY);
			SET v_table_users_tz = CONCAT(v_tablename, "_users_tz");
			SET v_overtime = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL - 2 DAY),"%Y-%m-%d");
			SET @s = CONCAT("delete from ", v_table_users_tz, " where `time` < '", v_overtime, "'");
			PREPARE stmt FROM @s;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;

			SET @s = CONCAT("delete from ", v_tablename, " where `kgtime` < '", v_overtime, "'");
			PREPARE stmt FROM @s;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;*/
    }

    if ($p_specifyno == 0) {
        //-- 取开始期号
        $sql = "SELECT id,kgtime FROM $v_tablename  ORDER BY id DESC LIMIT 1";
        echo $sql;
        $result=$db->fetch_first($sql);
        echo "\r\n".'----获取期号----'."\r\n";
        var_dump($result);
        echo "\r\n".'----获取期号----'."\r\n";
        $v_no = $result['id'];
        $v_no_time = $result['kgtime'];
        if ($v_no == null) {
            return array(array('code' => '', 'msg' => ''));
        }
    } else {
        $v_no = $p_specifyno;
        $sql = "SELECT kgtime FROM $v_tablename WHERE id = $v_no LIMIT 1";
        $res = $db->result_first($sql);
        $v_no_time = $res['kgtime'];
    }

    $sql = "SELECT no_interval_second,no_begin_time,no_end_time FROM game_catch_config WHERE gamekind = '$p_gamekind'";
    $res = $db->fetch_first($sql);
    echo '----no_interval_second   no_begin_time---';
    var_dump($res);
    echo '----no_interval_seconds----';
    $v_interval_second = $res['no_interval_second'];
    $v_begin_time = $res['no_begin_time'];
    $v_end_time = $res['no_end_time'];
    $sql = "SELECT game_std_odds FROM game_config WHERE game_type = $p_gametype";
    $res = $db->fetch_first($sql);
    $v_odds = $res['game_std_odds'];
    var_dump($v_i);
    var_dump($p_reccount);
    while ($v_i <= $p_reccount) {
        $v_no++;
        $v_i++;
        if ($p_gamekind == 'gamefast') {

        } elseif ($p_gamekind == 'gamebj' || $p_gamekind == 'gamepk') {
            echo "\r\n----v_no-o---------"."\r\n";
            var_dump($v_no_time);
            echo "\r\n";
            var_dump($v_begin_time);
            echo "\r\n";
            var_dump(strtotime($v_begin_time));
            echo "\r\n";
            var_dump(date('Y-m-d H:i:s',strtotime($v_begin_time)));
            echo "\r\n";
            echo "\r\n";
            var_dump(strtotime(date('H:i:s',strtotime($v_no_time)+$v_interval_second)));
            echo "\r\n";
            if(strtotime(date('H:i:s',strtotime($v_no_time)+$v_interval_second))<strtotime($v_begin_time)){
                echo 11;
                $v_no_time =date('Y-m-d 00:00:00',strtotime($v_no_time)+$v_interval_second);
            }else{
                $v_no_time = date('Y-m-d H:i:s',strtotime($v_no_time)+$v_interval_second);
            }
        }
        $sql="insert into $v_tablename (id,kgtime,gfid,zjpl) values('$v_no','$v_no_time','$v_no','$v_odds')";
        echo "\r\n";
        echo $sql;
        echo "\r\n";
        $db->query($sql);
    }

}

$db->close();
